import csv


def sort_by_column(csv_cont, value_mapper, has_header=True, reverse=False):
    header = None
    body = csv_cont
    if has_header:
        header = csv_cont[0]
        body = csv_cont[1:]
    body = sorted(body,
                  key=value_mapper,
                  reverse=reverse)
    if has_header:
        body.insert(0, header)
    return body


def csv_to_list(csv_file, delimiter=',', encoding='utf-8'):
    with open(csv_file, 'r', encoding=encoding, errors='ignore') as csv_con:
        reader = csv.reader(csv_con, delimiter=delimiter)
        return list(reader)


def list_to_csv(csv_file, content, delimiter=',', encoding='utf-8'):
    with open(csv_file, 'w', encoding=encoding, newline='', errors='ignore') as csv_con:
        writer = csv.writer(csv_con, delimiter=delimiter)
        writer.writerows(content)


def sort(in_file, out_file, column, reverse):
    content = csv_to_list(in_file)
    content = sort_by_column(content, lambda x: float(x[column]), False, reverse)
    list_to_csv(out_file, content)


def exchange(in_file, out_file, column1, column2):
    content = csv_to_list(in_file)
    for row in content:
        row[column1], row[column2] = row[column2], row[column1]
    list_to_csv(out_file, content)


def remove(in_file, out_file, column):
    content = csv_to_list(in_file)
    for row in content:
        row.pop(column)
    list_to_csv(out_file, content)
